package cn.edu.njuit.webserver.securityserver.service.impl;

import cn.edu.njuit.webserver.securityserver.entity.SmsCodeStore;
import cn.edu.njuit.webserver.securityserver.service.SmsService;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @Description: 实现短信服务
 * @Data: 2022/9/8 15:37
 * @Author: guzy
 */

@Service
public class AliyunSmsService implements SmsService {
    @Value("${sms.aliyun.accessKeyId}")
    String accessKeyId;
    @Value("${sms.aliyun.accessKeySecret}")
    String accessKeySecret;
    @Value("${sms.aliyun.signName}")
    String signName;
    @Value("${sms.aliyun.templateCode}")
    String templateCode;

    /**
     * 发送短信验证码
     *
     * @param phone ⼿机号码
     * @return
     */
    @Override
    public boolean sendValidateSms(String phone) {
        //获得6位⻓度的验证码
        String code = this.getRandomCode(6);
        //如果映射表中有该⼿机号码的验证码记录，直接使⽤此验证码重新发送。
        if (SmsCodeStore.codeStore.containsKey(phone)) {
            code = SmsCodeStore.codeStore.get(phone);
        }
        try {
            //调⽤初始化客户端⽅法，得到阿⾥云调⽤客户端对象
            Client smsClient = this.getClient(accessKeyId, accessKeySecret);
            //发送短信验证码请求：参数内容具体参考阿⾥云短信服务开发⽂档
            SendSmsRequest sendSmsRequest = new
                    com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setPhoneNumbers(phone) //⼿机号码
                    .setSignName(this.signName) //短信服务签名
                    .setTemplateCode(this.templateCode) //短信模板
                    .setTemplateParam("{\"code\":\"" + code + "\"}"); //短信内容参数，将验证码填⼊短信。
            smsClient.sendSms(sendSmsRequest); //发送短信
            //短信发送成功后，将⼿机号与验证码写⼊映射表。
            SmsCodeStore.codeStore.put(phone, code);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param phone ⼿机号码
     * @param code  待验证的验证码
     * @return
     */
    @Override
    public boolean validateSms(String phone, String code) {
        if (SmsCodeStore.codeStore.containsKey(phone)) {
            //从映射表中读出正确验证码
            String correctCode = SmsCodeStore.codeStore.get(phone);
            //如果验证码与输⼊验证码⼀致，验证通过
            if (correctCode.equals(code)) {
                //验证通过，需要将⼿机号码从映射表中移除。
                SmsCodeStore.codeStore.remove(phone);
                return true;
            }
        }
        return false;
    }

    //实现验证码⽣成算法：随机产⽣指定位数的数字。
    private String getRandomCode(Integer length) {
        String code = "";
        Random r = new Random();
        for (int i = 0; i < length; i++) {
            code += String.valueOf(r.nextInt(10));
        }
        return code;
    }

    /**
     * 获取阿⾥云客户端
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     */
    private Client getClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

}
